package com.tengju.bff.interfaces.covercharge.service.letax.impl;

import com.alibaba.fastjson.JSONObject;
import com.tengju.bff.interfaces.covercharge.constant.LetaxReturnCodeEnum;
import com.tengju.bff.interfaces.covercharge.service.letax.LeTaxClient;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeEnum;
import com.tengju.bff.interfaces.covercharge.entity.vo.ServiceLetaxRegisteredReturnResult;
import com.tengju.bff.interfaces.covercharge.entity.vo.SearchMerchantInfoVo;
import com.tengju.bff.interfaces.covercharge.entity.vo.SearchMerchantInfoDetailVo;
import com.tengju.bff.interfaces.covercharge.util.MD5Utils;
import com.zoi7.component.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * @author cj
 * @date 2020/12/01
 * @description 乐税服务实现
 */
@Slf4j
@Service
public class LeTaxServiceImpl {

    public final String coreCompanyId = "TJ";

    @Value("${letax.appKey}")
    private String letaxAppKey;

    @Value("${letax.appSecret}")
    private String letaxAppSecret;

    @Value("${letax.open}")
    private String letaxOpenDomain;

    @Value("${letax.mlsxz}")
    private String letaxMlsxzDomain;

    /**
     * 获取token
     *
     * @return 结果
     */
    public String getToken() {
        Map result = null;
        try {
            String reqUrl = letaxOpenDomain + "getToken?"
                    + "appKey=" + letaxAppKey + ""
                    + "&appSecret=" + letaxAppSecret;
            log.info("[服务费][乐税获取token参数]：" + reqUrl);
            result = LeTaxClient.sendGet(reqUrl);
            log.info("[服务费][乐税获取token结果]：" + result);
        } catch (Exception e) {
            log.error("[服务费][乐税token获取异常,异常信息]:", e);
            throw new ServiceException("乐税token获取异常");
        }
        if (result.get("error") != null) {
            throw new ServiceException(result.get("error").toString());
        }
        if (result.get("token") == null) {
            throw new ServiceException("乐税获取token返回为空");
        }
        return result.get("token").toString();
    }

    /**
     * 获取商户信息
     *
     * @return 结果
     */
    public ServiceLetaxRegisteredReturnResult searchMerchantInfo(Integer idCode) {
        Assert.notNull(idCode, "代理id不能为空");

        Map result = null;
        String token = getToken();
        SearchMerchantInfoVo searchMerchantInfoVo = new SearchMerchantInfoVo();
        searchMerchantInfoVo.setToken(token);
        SearchMerchantInfoDetailVo searchMerchantInfoDetailVo = new SearchMerchantInfoDetailVo();
        searchMerchantInfoDetailVo.setCoreCompanyId(coreCompanyId);
        searchMerchantInfoDetailVo.setCoreCompanyMerchantId(String.valueOf(idCode));
        searchMerchantInfoVo.setHead(searchMerchantInfoDetailVo);
        try {
            log.info("[服务费][获取商户信息参数]：" + searchMerchantInfoVo.toString());
            String reqUrl = letaxOpenDomain + "api/getMerchantInfo";
            result = LeTaxClient.sendPost(reqUrl, searchMerchantInfoVo);
            log.info("[服务费][获取商户信息结果]：" + result);
        } catch (Exception e) {
            log.error("[服务费][获取商户信息获取异常,异常信息]:", e);
            throw new ServiceException("获取商户信息获取异常");
        }
        if (result.get("head") == null || result.get("body") == null) {
            throw new ServiceException("商户信息为空");
        }

        //head返回数据
        JSONObject headObject = (JSONObject) JSONObject.parse(result.get("head").toString());
        if (!LetaxReturnCodeEnum.SUCCESS.getCode().equals(headObject.get("rtnCode").toString())) {
            throw new ServiceException(headObject.get("rtnMsg").toString());
        }

        //body返回数据
        JSONObject bodyObject = (JSONObject) JSONObject.parse(result.get("body").toString());
        if (!LetaxReturnCodeEnum.SUCCESS.getCode().equals(bodyObject.get("bizCode").toString())) {
            throw new ServiceException(bodyObject.get("bizMsg").toString());
        }

        Assert.notNull(bodyObject.get("merchantInfo").toString(), "商户信息为空");

        //商户信息
        JSONObject merchantInfoObject = (JSONObject) JSONObject
                .parse(bodyObject.get("merchantInfo").toString());

        ServiceLetaxRegisteredReturnResult serviceLetaxRegisteredReturnResult = new ServiceLetaxRegisteredReturnResult();
        serviceLetaxRegisteredReturnResult.setMerchantId(merchantInfoObject.get("merchantId").toString());
        serviceLetaxRegisteredReturnResult.setMerchantName(merchantInfoObject.get("merchantName").toString());
        serviceLetaxRegisteredReturnResult.setMerchantTaxNumber(merchantInfoObject.get("merchantTaxNumber").toString());
        serviceLetaxRegisteredReturnResult.setLicenseUrl(merchantInfoObject.get("licenseUrl").toString());
        serviceLetaxRegisteredReturnResult.setLicenseCopyUrl(merchantInfoObject.get("licenseCopyUrl").toString());
        serviceLetaxRegisteredReturnResult.setName(merchantInfoObject.get("name").toString());
        serviceLetaxRegisteredReturnResult.setIdCardNo(merchantInfoObject.get("idCardNo").toString());
        serviceLetaxRegisteredReturnResult.setPhoneNumber(merchantInfoObject.get("phoneNumber").toString());
        serviceLetaxRegisteredReturnResult.setEmail(merchantInfoObject.get("email").toString());
        serviceLetaxRegisteredReturnResult.setPoliticalAppearance(merchantInfoObject.get("politicalAppearance").toString());
        serviceLetaxRegisteredReturnResult.setDegreeEducation(merchantInfoObject.get("degreeEducation").toString());
        serviceLetaxRegisteredReturnResult.setStateCode(merchantInfoObject.get("stateCode").toString());
        serviceLetaxRegisteredReturnResult.setRejectType(merchantInfoObject.get("rejectType").toString());
        serviceLetaxRegisteredReturnResult.setRejectReason(merchantInfoObject.get("rejectReason").toString());
        serviceLetaxRegisteredReturnResult.setIfFaceAuthenticate(merchantInfoObject.get("ifFaceAuthenticate").toString());
        serviceLetaxRegisteredReturnResult.setOpeningDate(merchantInfoObject.get("openingDate").toString());
        serviceLetaxRegisteredReturnResult.setMerchantAddress(merchantInfoObject.get("merchantAddress").toString());

        return serviceLetaxRegisteredReturnResult;
    }

    /**
     * h5登录
     *
     * @return 结果
     */
    public String h5Login(Integer idCode) {
        Assert.notNull(idCode, "代理id不能为空");
        String ticket = MD5Utils.convertMD5(String.valueOf(idCode));
        return letaxMlsxzDomain + "sign?"
                + "coreCompanyId=" + coreCompanyId + ""
                + "&coreCompanyMerchantId=" + idCode + ""
                + "&ticket=" + ticket;
    }

    public String registeredCode(Integer idCode) {
        Assert.notNull(idCode, "代理id不能为空");
        return letaxMlsxzDomain + "sign?"
                + "coreCompanyId=" + coreCompanyId + ""
                + "&coreCompanyMerchantId=" + idCode;
    }
}
